<!-- 柱状图 -->
<template>
  <div class="echarts" :id="id"></div>
</template>
<script setup lang='ts'>
import { onMounted, watch } from 'vue'
import * as echarts from 'echarts'
const props = defineProps({
  id: {
    type: String,
    default: 'echarts'
  },
  text: {
    type: String,
    default: ''
  },
  data: {
    type: Array,
    default: []
  },
  colors: {
    type: Array,
    default: ['#9285FF']
  }
})
const initEcharts = () => {
  // 基于准备好的dom，初始化echarts实例
  const myChart = echarts.init(document.getElementById(props.id))
  const xdata = props.data.map((item: any) => item.name)
  const ydata = props.data.map((item: any) => item.number)
  const option = {
    color: props.colors,
    title: {
      text: props.text
    },
    grid: {
      top: "40px",
      left: "55px",
      right: "10px",
      bottom: "40px"
    },
    xAxis: {
      type: 'category',
      data: xdata,
      axisLabel: {
        interval: 0,
        rotate: 40,
        textStyle: {
          fontSize: 10,
          color: '#333'
        }
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: ydata,
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ]
  }
  // 绘制图表
  myChart.setOption(<echarts.EChartsCoreOption>option);
}
watch(() => props.data, () => {
  initEcharts()
})
onMounted(() => {
  initEcharts()
})
</script>

<style scoped lang="scss">
.echarts {
  width: 100%;
  height: 100%;
}
</style>